<?php


namespace Xtsb\Cims\Ocr\Invoice;


use Xtsb\Cims\File\File;
use Xtsb\Cims\File\Image;
use app\Http\Finance\Servers\FinanceInvoicePageServer;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

class BaseOcr
{

  static $request;
  static $save_name;
  static $request_url;

  static $header = [
    'Authorization' => 'APPCODE 44a54701b3254629a4ab4a0daac7e680',
    'User-Agent' => 'Apifox/1.0.0 (https://apifox.com)',
    'Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8',
  ];

  static function getHost(){
    return "http://".\Request()->host().'/storage/';
  }

  static function getRequest($options,$method='GET'){
    $request = new Request($method, static::$request_url, self::$header);
    $res = (new Client(['verify'=>false]))->sendAsync($request, $options)->wait();
    $data =  $res->getBody();
    return $data;
  }
  
  static function getFileName(){
    $file = request()->file('files');
    $dirname = request()->param('dirname', 'excel'); //文件保存目录

    $savename = \think\facade\Filesystem::disk('public')->putFile($dirname, $file,
      function () use ($file) {
        $fileName = md5(str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName()));
        return $fileName;
      });
    self::$save_name = $savename;
    return $savename;
  }


  static function replaceInvoiceDate($date){
    $date = str_replace('年','-',$date);
    $date = str_replace('月','-',$date);
    return  str_replace('日','',$date);
  }

  static function replaceTaxRate($rate){
    return (int) str_replace('%','',$rate);
  }

  static function delete_file()
  {
    @unlink('./storage/' . self::$save_name);//删除文件
  }


  //文件数 识别检测点数成功失败数
  static $file_num = 0;  
  static $point_suc = 0; 
  static $point_err = 1;
  
  //获取对应的图片链接
  static function getImageUrlByRemote($dirname, $file_name,$size_limit=1.9){
    $ip = get_image_ip_addr();
    $info = pathinfo($file_name);
    $extension = $info['extension'] ?? "";
    $file_url = "$ip/$dirname/$file_name";
    $file_url2 = $ip.'/'.urlencode($dirname).'/'.urlencode($file_name);
    $file_info = File::fileInfo(["$dirname/$file_name"]);
    if(isset($file_info['data']) && isset($file_info['data'][0])){
      $size = (float) $file_info['data'][0]['size']/1024;
      if($size>$size_limit){
        $local_file = self::localFileStore($file_url, $info);
        $file_url2 = $local_file['url'];
      }
    }
    return $file_url2;
  }

  //返回给前端用户的识别信息
  static function ocrMessage($remain_error,$type='发票'){
    $message = [];
    $file_num = self::$file_num;
    $file_suc = self::$point_suc;
    $file_err = self::$point_err;
    if($file_num >0){
      $message[] = "共上传<span class='text-blue'>{$file_num}张{$type}</span>";
    }
    if($file_suc>0){
      $message[] = "<span class='text-green'>识别成功：{$file_suc}张</span>";
    }
    if($file_err>0){
      $message[] = "<span class='text-red'>识别失败：{$file_err}张</span>";
    }
    if(!empty($remain_error)){
      $temp = $file_num-$file_suc-$file_err;
      $message[] = "<span class='text-gray'>{$temp}张发票尚未识别:</span>  {$remain_error}";
//      $has_error = true;
    }else{
      if(FinanceInvoicePageServer::REMAIN_CHECK){
        $message[] = "剩余可用识别次数: ".FinanceInvoicePageServer::remainOcrNumber();
      }
    }
    $message = implode('<br>', $message);
    return $message;
  }

  //文件操作处理
  static function localFileStore($url, $file_info){
    $file_name = $file_info['basename'];
    $local_name = "./storage/temp/".$file_name;
    if(!file_exists("./storage/temp/")){
      mkdir("./storage/temp/");
    }
    $res = file_put_contents($local_name,self::getData($url));

    $result = ['url'=>null, 'local_name'=>$local_name];
    if(!$res){
      return $result;
    }
    Image::thumb($local_name,true,[920,720]);
    $result['url'] = "http://".\Request()->host().'/'."storage/temp/".urlencode($file_name);
    return $result;
  }

  static function getData($url){
    $ch = curl_init(); // 初始化 CURL
    curl_setopt($ch, CURLOPT_URL, $url); // 设置请求 URL
    curl_setopt($ch, CURLOPT_HEADER, false); // 不显示响应头信息
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回原生的内容，而不是直接输出
    $data = curl_exec($ch); // 发送请求
    curl_close($ch); // 关闭 CURL
    return $data;
  }

}